package casel.info.onceuponatime;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.corba.se.impl.util.Version;

/**
 * @author Mikel Castillo Casel
 * @version 1.0
 */
@WebServlet("/New")
public class New extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public New() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.getServletContext().
		getRequestDispatcher("/new.jsp").
			forward(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		createTale(request.getParameter("title"), request.getParameter("tale"));
		this.getServletContext().
		getRequestDispatcher("/Home").
			forward(request,response);
		
	}
/**
 * insert tale into database
 * @param title
 * @param tale
 */
	private void createTale(String title, String tale) {
String urlcon = "jdbc:mysql://localhost:3306/onceupon";
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection taleConn = 
					DriverManager.getConnection(urlcon, "root","");
			String insertSQL= "insert into tale(title,tale) values(?, ?)";
			PreparedStatement prep = taleConn.prepareStatement(insertSQL);
			
			prep.setString(1, title);
			prep.setString(2, tale);
			prep.addBatch();
			prep.executeBatch();
			
			taleConn.close();
					
		} catch (Exception e) {
			
			 e.printStackTrace();
			 
		}
		
		
	}

}
